﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PDX.ChangeTracking
{
    /// <summary>
    /// Locates the <see cref="ISnapshotHandler"/> for a given <see cref="Editor"/>.
    /// Uses the <see cref="Scope.ChangeTrackingScopeProperty"/>.
    /// </summary>
    public class SnapshotHandlerLocator
    {
        /// <summary>
        /// Gets the recorder.
        /// </summary>
        public ISnapshotHandler Handler { get; private set; }

        /// <summary>
        /// Gets the target.
        /// </summary>
        public Editor Target { get; private set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="SnapshotHandlerLocator"/> class.
        /// </summary>
        /// <param name="editor">The editor.</param>
        public SnapshotHandlerLocator(Editor editor)
        {
            this.Target = editor;

            editor.DependencyPropertyChanged += new System.Windows.DependencyPropertyChangedEventHandler(editor_DependencyPropertyChanged);
            Relocate();
        }

        void editor_DependencyPropertyChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e)
        {
            if (e.Property == Scope.ChangeTrackingScopeProperty)
            {
                Relocate();
            }
        }

        void Relocate()
        {
            var scope = Scope.GetChangeTrackingScope(Target);
            var handler = scope as ISnapshotHandler;
            if (handler != null)
            {
                Handler = handler;
            }
        }
    }
}
